import java.util.LinkedList;

public class MiddleCodeTable {
    private final LinkedList<FourTuple> table;
    int NXQ;

    // 返回四元式列表长度
    public int getNXQ() {
        return table.size();
    }

    // 初始化
    public MiddleCodeTable() {
        table = new LinkedList<>();
    }

    // 添加四元式列表
    public boolean add(String symbol, String operand1, String operand2, String result) {
        this.table.addLast(new FourTuple(symbol, operand1, operand2, result));
        return true;
    }
    // 回填四元式列表
    public boolean backPath(int index, String result){
        if(index < 0 || index > table.size()) return false;
        int counter = 0;
        for(FourTuple ft: table){
            if (counter == index) {
                ft.result = result;
                this.table.set(index, ft);
                return true;
            }
            counter ++;
        }
        return true;
    }

    // 生成四元式列表
    public String dump() {
        StringBuilder s = new StringBuilder();
        int count = 0;
        s.append("code table:\n");
        for (FourTuple fourTuple : table) {
            s.append("(").append(count).append(")");
            count ++;
            s.append("(").append(fourTuple.symbol).append(", ").append(fourTuple.operand1).append(", ").append(fourTuple.operand2).append(", ").append(fourTuple.result).append(")").append("\n");
        }
        return s.toString();
    }

    // 清理四元式列表
    public void clear() {
        table.clear();
    }
}
